package com.android.binderserverclient0.mvi2.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.android.binderserverclient0.mvi2.intent.MainIntent
import com.android.binderserverclient0.mvi2.repository.MainRepository
import com.android.binderserverclient0.mvi2.state.MainState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class MainViewModel(private val repository: MainRepository) : ViewModel() {

    //创建意图管道,不限制容量.
    val mainIntentChannel = Channel<MainIntent>(Channel.UNLIMITED)

    //可变状态数据流
    private val mState = MutableStateFlow<MainState>(MainState.Idle)

    //可观察状态数据流
    val outputState : StateFlow<MainState>
        get() = mState

    init {
        viewModelScope.launch {
           mainIntentChannel.consumeAsFlow().collect {
               when (it) {
                   is MainIntent.GetWallPaper -> {
                       getWallPaper()
                   }
               }
           }
        }
    }

    private fun getWallPaper() {
        viewModelScope.launch {
            //修改状态为加载中
            mState.value = MainState.Loading
            //网络请求
            mState.value = try {
                MainState.GetWallPapers(repository.getWallPapers())
            } catch (ex: Exception) {
               MainState.Error(ex.message ?: "error")
            }
        }
    }

}